<template>
    <el-container class="layout-page layout-container">
        <!-- 头部导航 START -->
        <el-header class="contain-top">
            <div v-title :data-title="hospitalName"></div>
            <div class="contain-nav">
                <div class="nav-left">
                    <div class="nav-logo" v-if="logoUrl"><img :src="logoUrl" alt=""></div>
                    <div class="nav-title">{{hospitalName}}</div>
                </div>
                <div class="pttitle" v-if="isVideo == false">
                    <div>
                        <div class="mouse-pointer" @click="gotoHomePage">
                            首页
                            <!-- <i class="iconfont iconhome" style="font-size: 24px;"></i> -->
                        </div>
                    </div>
                    <div class="inquiry-btn">
                        <div @click="gotoInquiry" class="mouse-pointer">
                            {{ $authInfo.getAuthType() == 'P' ||  $authInfo.getAuthType() == 'P' ? '病例管理': '网络问诊'}}
                        </div>
                    </div>
                    <div class="mouse-pointer" v-if="isUser" @click="gotoPrescription">
                        我的处方
                    </div>
                    <div class="mouse-pointer" v-if="isUser" @click="gotoUserInquiry">
                        我的问诊
                    </div>
                    <div class="mouse-pointer" @click="gotoUser">
                        个人中心
                    </div>

                    <div>
                        <div class="mouse-pointer" @click="gotoGuidePage">
                            <!-- <i class="iconfont iconhelp" style="font-size: 24px;"></i> -->
                            常见问题
                        </div>
                    </div>
                    <!-- 角色=医生，显示“消息中心”图标 -->
                    <div>
                        <div class="mouse-pointer" @click="gotoNofity">
                            消息中心
                        </div>
                    </div>
                    <div class="mouse-pointer" @click="gotoRemoteConsult">
                        远程会诊
                    </div>
                    <div>
                        <div v-if="ifHasToken == true">
                            <span class="pttitle-name">{{trueName}}</span>
                            <el-divider direction="vertical" class="pttitle-line"></el-divider>
                            <div @click="outLogin" class="pttitle-out">退出登录</div>
                        </div>
                        <router-link class="login-btn" v-else to="/login">登录/注册</router-link>
                    </div>
                </div>
                <div class="pttitle pttitle-room" v-else>
                    <div>
                        <span>{{trueName}}</span>
                        <el-divider direction="vertical"></el-divider>
                        <div @click="outVideoRoom" style="display:inline-block;">退出问诊</div>
                    </div>
                </div>
            </div>
        </el-header>
        <!-- 头部导航 END -->

        <!-- 主要内容 START -->
        <el-main>
            <section class="layout-content">
                <router-view></router-view>
            </section>
        </el-main>
        <!-- 主要内容 END -->

        <!-- 底部 -->
        <el-footer class="layout-full-media-box container-footer">
            <div class="contain-nav">
                <div class="nav-left">
                    <div class="nav-logo" v-if="logoUrl"><img :src="logoUrl" alt=""></div>
                    <div class="footer-title nav-title">{{hospitalName}}</div>
                </div>
                <div class="bottom-pttitle">
                    <div class="pttitle">
                        <div class="mouse-pointer" @click="gotoHomePage">
                            <!-- <img src="@/assets/img/top_home.png" alt=""> -->
                            首页
                        </div>
                        <div class="inquiry-btn mouse-pointer">
                            <template v-if="!isUser">
                                <div @click="gotoInquiry">问诊中心</div>
                            </template>
                            <a @click="goMini()" v-else>问诊中心</a>
                        </div>
                        <div class="mouse-pointer" v-if="isUser" @click="gotoPrescription">我的处方</div>
                        <div class="mouse-pointer" @click="gotoUserInquiry">我的问诊</div>
                        <div class="mouse-pointer" @click="gotoUser">个人中心</div>
                        <div class="mouse-pointer" @click="openServer">隐私声明</div>
                    </div>
                    <div class="text-color">
                        <span style="padding-right:50px">
                            <a href="https://beian.miit.gov.cn/" target="_blank">{{$global.bottomNumber}}</a>
                        </span>
                        <span>{{$global.bottomName}}</span>
                    </div>
                </div>
            </div>
        </el-footer>

        <!--隐私弹框 start-->
        <el-dialog class="dialog-frame" width="600" title="隐私声明" :visible.sync="serverDialog" @close="serverDialog = false" :close-on-click-modal="false" :close-on-press-escape="false">
            <div class="ql-snow ql-editor" v-html="serverHtml"></div>
        </el-dialog>
        <!--隐私弹框 end -->

        <go-mini-dialog v-if="goMiniVisible" ref="goMini"></go-mini-dialog>

        <el-dialog class="dialog-frame inquiry-dialog" width="600" title="提示" :visible.sync="inquiryDialog" :close-on-click-modal="false" :close-on-press-escape="false" :show-close="false">
            <div>您上一个{{inquiryType == '1' ? '视频问诊':'图文问诊'}}还在进行中，患者仍在聊天室内等候您，请点击重新连接。</div>
            <div class="btn-size">
                <el-button @click="cancelBtn">不便接诊</el-button>
                <el-button @click="confirmBtn" type="primary">重新连接</el-button>
            </div>
        </el-dialog>
          <!-- 呼叫弹窗 -->
          <call-dialog
              :visible="showCallDialog"
              :roomId="waitList.length && waitList[waitList.length - 1].roomId"
              @accept="handleAcceptCall"
              @reject="handleRejectCall"
          />
    </el-container>
</template>


<script>
    import goMiniDialog from '../inquiry/userinquiry/go-mini-dialog'
    import CallDialog from "../remoteConsult/myConsult/CallDialog.vue";
    export default {
        components: {
          CallDialog,
            goMiniDialog
        },
        data() {
            return {
                isVisitor: true,
                isUser: false,
                goMiniVisible: false,
                isHome: false,
                trueName: '',
                ifHasToken: false,
                isVideo: false,
                serverDialog: false, //服务隐私协议弹框
                serverHtml: '',
                inquiryType: '', //历史问诊类型
                socketMsg: {},
                dataToken: '',
                inquiryDialog: false,
                logoUrl: '',
                hospitalName: '',


                /**
                 * 待会诊列表
                 */
                waitList: [],
                waitDialog: false,
                /**
                 * 待会诊2
                 */
                showCallDialog: false
            };
        },
        created() {
            if (this.$authInfo.webToken() && this.$route.path == '/video') {
                var wsuri = "wss://" + this.$global.socketName + "/websocket"
              console.log(';wsuri',wsuri)
                this.$setWs.initWebSocket(wsuri, this.$authInfo.webToken());
            }
          /**
           * 创建会诊室 startConsult
           */

          if (this.$authInfo.webToken()) {
            const wsuri = "wss://" + this.$global.remoteSocket;
            this.$setWsRemote.initWebSocket(wsuri, this.$authInfo.webToken());
          }
        },
        computed: {
            //在computed方法声明并存储到vuex
            getWsMsg() {
                return this.$store.state.webSocketMsg;
            },
            getWsRemoteMsg() {
              return this.$store.state.webSocketMsgRemoteMsg;
            },
        },
        watch: {
            $route(to, from) { // 检测路由变化
                this.isVideo = this.$route.path == '/video' || this.$route.path == '/prescription';

                if (this.$route.path == '/video' && this.$authInfo.webToken()) {
                    let para = {
                        working: 1,
                    }
                    this.$ajax.receivePatients(para).then(res => {
                        // this.$router.push('/video');
                    }).catch(err => {
                        this.$message({
                            message: err.msg,
                            type: 'error',
                        })
                    })
                }

                this.ifHasToken = !!this.$authInfo.webToken();
            },
            // ifHasToken(val) {
            //     if (val == '') {
            //         this.$router.push('/login');
            //     }
            // },
            getWsMsg(data, val) {
                if (data != 'pong' && data != '') {
                    if (data.packageType == 7) { //获取患者加入房间事件
                        console.log(data, '------------------获取患者加入房间事件-------------------')
                        this.inquiryType = data.inquiryType
                        this.socketMsg = data
                        this.$setStore('inquiryMsg', data)
                        if (this.$route.path != '/video' && !this.$store.state.remoteId && !this.$route.path.includes('remoteConsult')) {
                            this.inquiryDialog = true
                        }
                    }
                }
            },

          //监听
          getWsRemoteMsg(data, val) {
            if (data != "pong" && data != "") {
              let packageType = 0
              if (data.code) {
                packageType = data.code
              } else {
                // if (data.configuration) {
                //   packageType = data.configuration.packageType
                // }
              }
              switch (packageType) {
                case 3:
                  console.log('广播邀请加入',data)
                  let find = this.waitList.find(item => item.roomId === data.roomId)
                  if (!find) {
                    this.waitList.push({
                      ...data
                    })
                    if (this.$route.path !== '/startConsult') {
                      this.showCallDialog = true
                    }
                  }
                  break
              }
            }
          },
        },
        methods: {
            // 邀请用户加入房间
            inviteUserJoinRoom(data) {
              // let {
              //   receiverID,// 邀请人id
              //   receiverType,// 邀请人类型
              //   roomId,// 房间id
              //   message,// 邀请消息
              //   packageType,// 包类型
              // }
            },
          async handleAcceptCall() {
            let current = this.waitList[this.waitList.length - 1]
            this.showCallDialog = false
            this.joinChannel(current)
          },
          handleRejectCall() {
            this.showCallDialog = false
            this.$message({
              type: 'info',
              message: '您已拒绝加入会议'
            })
            this.waitList = []
          },
          joinChannel(data) {
            // 加入会诊室
            this.$setWsRemote.send(5, {
              roomId: data.roomId,
              packageType: 3,
              timestamp: new Date().getTime()
            });
            this.$router.push({
              path: '/startConsult',
              query: {
                id: data.roomId
              }
            })
          },
            getHomeLogo() {
                this.$ajax.getHomeLogo().then(res => {
                    this.logoUrl = res.data || ''
                })
            },
            gotoHomePage() { //首页
                this.$router.push('/home')
            },
            gotoGuidePage() { //指南
                this.$router.push('/guide')
            },
            gotoPrescription() { //我的处方
                if (!this.$authInfo.webToken()) {
                    this.$router.push('/login')
                } else {
                    this.$router.push('/myprescription')
                }
            },
            // 前往用户端-我的问诊
            gotoUserInquiry() {
                if (!this.$authInfo.webToken()) {
                    this.$router.push('/login')
                } else {
                    this.$router.push('/myInquiry')
                }
            },
            gotoUser() { //个人中心
                if (!this.$authInfo.webToken()) {
                    this.$router.push('/login')
                } else {
                    this.$router.push('/user')
                }
            },
            gotoLogin() { //登录
                this.$router.push('/login')
            },
            outLogin() { //退出登录
                /* --- test: 更改退出时，的关闭socket节点 --- */
                let token = this.$authInfo.webToken();

                let data = {
                    webToken: token,
                    packageType: 2,
                }
                this.$setWs.logout(data);

                if (token) {
                    this.$ajax.outLogin({ webToken: token }).then(res => {
                        this.$message({
                            message: res.msg,
                            type: 'success',
                        })

                        /* let data = {
                            webToken: this.$authInfo.webToken(),
                            packageType: 2,
                        }
                        this.$setWs.send(2, data); */
                        // this.$setWs.onClose();

                    }).catch(err => {
                        this.$message.closeAll();
                    })
                }

                sessionStorage.clear();
                this.$router.push('/login');
            },
            gotoInquiry() { // 网络问诊
                if (!this.$authInfo.webToken()) {
                    this.$router.push('/login')
                } else {
                    this.$router.push('/inquiry')
                }
            },
            outVideoRoom() { //退出问诊状态
                if (!this.$authInfo.webToken()) {
                    this.$router.push('/login')
                } else if (this.$route.path == '/prescription') {
                    this.$router.push('/inquiry')
                    this.isVideo = false;

                    sessionStorage.autoLogId = '';
                    sessionStorage.autoPatientId = '';
                } else {
                    let logId = Number(this.$getStore('logId'))
                    this.$confirm(`您确定要暂停接诊吗？暂停后已排队候诊的患者无法发起视频、图文问诊。请谨慎操作。`, '退出问诊', {
                        customClass: 'l-confirm',
                        confirmButtonText: '确定',
                        cancelButtonText: '取消',
                    }).then(() => {
                        if (this.$getStore('logId') != null && this.$getStore('logId')) {
                            // console.log(this.$getStore('inquirySize'), typeof(this.$getStore('inquirySize')), 'this.$getStore:inquiryType')
                            if (this.$getStore('inquirySize') == '3' || this.$getStore('inquirySize') == '4') {
                                let data = {
                                    doctorId: this.$authInfo.getUser().id, //医生id
                                    logId: logId, //本次问诊id
                                }
                                this.$setWs.send(32, data);
                                this.$router.push('/inquiry')
                            } else {
                                let data = {
                                    logId: logId,
                                    packageType: 13,
                                }
                                this.$setWs.send(13, data);

                                this.$ajax.unSuccessfulInquiry({ id: logId }).then(res => {
                                    this.$router.push('/inquiry')

                                    this.$setWs.send(41, { packageType: 41 });
                                    setTimeout(() => {
                                        this.$removeStore('logId')
                                        this.$removeStore('inquirySize')
                                        this.$removeStore('hospitalName')
                                        window.sessionStorage.removeItem('logId');
                                    }, 500)
                                }).catch(err => {
                                    this.$message({
                                        message: err.msg,
                                        type: 'error',
                                    })
                                })
                            }
                        } else {
                            console.log('=== 退出问诊房间 ===');

                            this.$setWs.send(41, {
                                // logId: -1,
                                packageType: 41,
                            });

                            // this.$router.push('/inquiry')
                        }
                        let para = {
                            working: 0,
                        }
                        this.$ajax.receivePatients(para).then(res => {
                            this.$router.push('/inquiry')
                            this.isVideo = false
                            // 结束本次问诊
                            this.$setWs.onClose();
                        }).catch(err => {
                            this.$message({
                                message: err.msg,
                                type: 'error',
                            })
                        })
                    }).catch(() => {})
                }
            },
            goMini() {
                this.goMiniVisible = true
                this.$nextTick(() => {
                    this.$refs.goMini.init()
                })
            },
            // 前往消息中心
            gotoNofity() {
                this.$router.push({
                    path: '/inquiry',
                    query: {
                        activeName: 'messageCenter'
                    }
                })
            },
            //进入远程会诊
            gotoRemoteConsult(){
                this.$router.push({
                    path: '/remoteConsult/myConsult',
                    query: {
                        activeName: 'remoteConsult'
                    }
                })
            },
            openServer() { //打开隐私协议
                this.serverDialog = true
                this.$ajax.getPrivacyPolicy().then(res => {
                    this.serverHtml = res.data.initKey
                }).catch(err => {

                })
            },
            confirmBtn() { //重新连接
                let type = this.inquiryType
                let respMsg = this.socketMsg.inquiryPatientInfoResp
                let para = {
                    working: 1,
                    inquiryType: type,
                }
                this.$ajax.receivePatients(para).then(res => {
                    this.$router.push('/video');
                }).catch(err => {
                    this.$message({
                        message: err.msg,
                        type: 'error',
                    })
                })
                if (type != '3' && type != '4') {
                    this.$ajax.frozenOrder({ logId: this.socketMsg.logId }).then(res => {
                        this.inquiryDialog = false;
                    }).catch(err => {
                        this.$message({
                            message: err.msg,
                            type: 'error',
                        })
                    })
                } else {
                    this.inquiryDialog = false;
                }

                let data = {
                    logId: this.socketMsg.logId, //问诊id
                    doctorIM: respMsg.doctorIM, //医生im
                    doctorName: respMsg.doctorName, //医生姓名
                    patientIM: respMsg.patientIM, //患者im
                    userId: respMsg.userId, //用户id
                    packageCode: 200,
                    packageMsg: '',
                    packageType: 26,
                }
                this.$setWs.send(26, data);
            },
            cancelBtn() { //不便重连
                let respMsg = this.socketMsg.inquiryPatientInfoResp
                this.$ajax.unSuccessfulInquiry({ id: this.socketMsg.logId }).then(res => {
                    let data = {
                        logId: this.socketMsg.logId, //问诊id
                        patientIM: respMsg.patientIM, //患者im
                        userId: respMsg.userId, //用户id
                        packageCode: 200,
                        packageMsg: '',
                        packageType: 25,
                    }
                    this.$setWs.send(25, data);
                    let dataF = {
                        logId: this.socketMsg.logId,
                        packageType: 13,
                    }
                    this.$setWs.send(13, dataF);
                    this.inquiryDialog = false;

                    this.$message({
                        message: '已取消该接诊',
                        type: 'success',
                    })
                }).catch(err => {
                    this.$message({
                        message: err.msg,
                        type: 'error',
                    })
                })
            },
            // confirmDialog() { //患者等待医生选择弹框
            //     this.inquiryDialog = true
            //     let type = this.inquiryType
            //     let respMsg = this.socketMsg.inquiryPatientInfoResp
            //     this.$confirm(`您上一个<strong style="color: #409EFF;">${type == '1' ? '视频问诊':type == '3' ? '视频+图文问诊':'图文问诊'}</strong>还在进行中，患者仍在聊天室内等候您，请点击重新连接。`, '提示', {
            //         customClass: 'l-confirm',
            //         confirmButtonText: '重新连接',
            //         cancelButtonText: '不便接诊',
            //         dangerouslyUseHTMLString: true,
            //         closeOnClickModal: false,
            //         closeOnPressEscapes: false,
            //         showClose: false,
            //     }).then(() => {
            //         this.$ajax.frozenOrder({ userId: respMsg.userId }).then(res => {
            //             let data = {
            //                 logId: this.socketMsg.logId, //问诊id
            //                 doctorIM: respMsg.doctorIM, //医生im
            //                 doctorName: respMsg.doctorName, //医生姓名
            //                 patientIM: respMsg.patientIM, //患者im
            //                 userId: respMsg.userId, //用户id
            //                 packageCode: 200,
            //                 packageMsg: '',
            //                 packageType: 26,
            //             }
            //             this.$setWs.send(26, data);
            //         }).catch(err => {
            //             this.$message({
            //                 message: err.msg,
            //                 type: 'error',
            //             })
            //         })
            //         this.gotoDoctorInquiry(type)
            //     }).catch(() => {
            //         this.$ajax.unSuccessfulInquiry({ id: this.socketMsg.logId }).then(res => {
            //             let data = {
            //                 logId: this.socketMsg.logId, //问诊id
            //                 patientIM: respMsg.patientIM, //患者im
            //                 userId: respMsg.userId, //用户id
            //                 packageCode: 200,
            //                 packageMsg: '',
            //                 packageType: 25,
            //             }
            //             this.$setWs.send(25, data);
            //             let dataF = {
            //                 logId: this.socketMsg.logId,
            //                 packageType: 13,
            //             }
            //             this.$setWs.send(13, dataF);
            //         }).catch(err => {
            //             this.$message({
            //                 message: err.msg,
            //                 type: 'error',
            //             })
            //         })
            //     })
            // },
            gotoDoctorInquiry(type) { //跳转至网络接诊
                // console.log(type)
                let para = {
                    working: 1,
                    inquiryType: Number(type),
                }
                this.$ajax.receivePatients(para).then(res => {
                    this.$router.push('/video');
                }).catch(err => {
                    this.$message({
                        message: err.msg,
                        type: 'error',
                    })
                })
            },
            getHospitalName() { //获取医院名字

                this.$ajax.getConfigureName().then(res => {
                    this.hospitalName = res.data.hospitalNamePc
                    this.$setStore('hospitalName', res.data.hospitalNamePc)
                    this.$util.title(this.hospitalName)
                    // this.$addStorageEvent(2, "hospitalName", res.data.hospitalNamePc);
                }).catch(err => {

                })
            },
        },

        mounted() {
            this.isHome = false;
            this.dataToken = this.$authInfo.webToken();

            this.getHomeLogo();
            this.getHospitalName();

            // window.addEventListener('setItem', (e) => {
            //     this.hospitalName = e.newValue
            //     console.log(e,'addEventListener');
            // });

            if (this.$authInfo.webToken()) { this.trueName = this.$authInfo.getUser().trueName }

            if (!this.$authInfo.webToken()) { //是否为登录状态
                this.ifHasToken = false
            } else {
                this.ifHasToken = true
            }
            if (this.$authInfo.getUser()) {
                this.isUser = JSON.parse(this.$getStore('adminUserInfo')).type === 'D' ? false : true;
                this.isVisitor = false;
            } else {
                this.isUser = false;
                this.isVisitor = true;
            }

            this.isVideo = this.$route.path == '/video' || this.$route.path == '/prescription';
            if (this.$route.path == '/video' && this.$authInfo.webToken()) {
                let para = {
                    working: 1,
                }
                this.$ajax.receivePatients(para).then(res => {
                    // this.$router.push('/video');
                }).catch(err => {
                    this.$message({
                        message: err.msg,
                        type: 'error',
                    })
                })
            }

        },
    };
</script>

<style lang="scss" src="@/style/public/layout.scss"></style>
